package io.gitee.gemini.utis;


import io.gitee.gemini.core.annotations.Check;
import io.gitee.gemini.core.exception.ParamCheckException;
import io.gitee.gemini.core.pools.RegexPool;

import java.lang.reflect.Field;


public class ObjUtil {

    private ObjUtil() {
    }


    /**
     * 根据{@link Check}注解校验参数
     *
     * @param obj 需要校验的对象
     * @throws ParamCheckException 参数被校验到抛出异常
     */
    public static void checkObjValue(Object obj) throws ParamCheckException {
        Field[] fields = ReflectUtil.getClassFields(obj.getClass());

        for (Field field : fields) {
            field.setAccessible(true);
            Check annotation = field.getAnnotation(Check.class);
            if (annotation == null) {
                continue;
            }
            Object o;
            try {
                o = field.get(obj);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }

            if (o == null) {
                throw new ParamCheckException(StrUtil.format("{}为null", field.getName()));
            }

            if (annotation.canEmpty()) {
                continue;
            }

            String objStr = o.toString();
            String replace = StrUtil.clearStr(objStr, RegexPool.L_CURLY_BRACES, RegexPool.R_CURLY_BRACES, RegexPool.L_SQUARE_BRACKETS, RegexPool.R_SQUARE_BRACKETS);
            if (replace.length() == 0) {
                throw new ParamCheckException(StrUtil.format("{}:{}", field.getName(), annotation.message()));
            }
        }
    }

}


